package com.zjxmyq.microserviceyida.service;


import com.zjxmyq.microserviceyida.domain.AccessTokenManager;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccessTokenInterceptor implements RequestInterceptor {

    private final AccessTokenManager accessTokenManager;

    @Autowired
    public AccessTokenInterceptor(AccessTokenManager accessTokenManager) {
        this.accessTokenManager = accessTokenManager;
    }

    @Override
    public void apply(RequestTemplate template) {
        // 在请求之前检查accessToken是否过期，如果过期则刷新
        if (accessTokenManager.isAccessTokenExpired()) {
            accessTokenManager.refreshAccessToken();
        }

        // 获取最新的accessToken
        String accessToken = accessTokenManager.getAccessToken();

        // 添加accessToken到请求Header中
        template.header("x-acs-dingtalk-access-token", accessToken);
    }
}
